package com.zn.opit.tech.easyexcel.domain;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 统一返回对象
 */
public class R extends LinkedHashMap<String, Object> {

    private static final long serialVersionUID = 1L;

    private R() {
        put("code", 200);
        put("msg", "success");
    }

    public static R ok() {
        return new R();
    }

    public static R ok(String msg) {
        R r = new R();
        r.put("msg", msg);
        return r;
    }

    public static R ok(Map<String, Object> map) {
        R r = new R();
        r.putAll(map);
        return r;
    }

    public R setData(Object data) {
        put("data", data);
        return this;
    }

    public R put(String key, Object value) {
        super.put(key, value);
        return this;
    }

    public <T> T getData(String key, TypeReference<T> typeReference) {
        Object data = get(key);// 默认是map
        String s = JSON.toJSONString(data);
        T t = JSON.parseObject(s, typeReference);
        return t;
    }

    // 利用fastjson进行逆转
    public <T> T getData(TypeReference<T> typeReference) {
        Object data = get("data");// 默认是map
        String s = JSON.toJSONString(data);
        T t = JSON.parseObject(s, typeReference);
        return t;
    }

    public static R error(String code, String msg) {
        R r = new R();
        r.put("code", code);
        r.put("msg", msg);
        return r;
    }
}
